package ipebg.mzk.provider.system.service.impl;

import ipebg.mzk.common.util.Page;
import ipebg.mzk.facade.entity.Org;
import ipebg.mzk.facade.entity.OrgLevel;
import ipebg.mzk.facade.system.service.OrgLevelService;
import ipebg.mzk.facade.system.service.OrgService;
import ipebg.mzk.facade.system.service.PagerService;
import ipebg.mzk.facade.system.service.UserService;
import ipebg.mzk.provider.system.dao.OrgLevelDao;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("orgLevelImpl")
@Transactional(rollbackFor = Exception.class)
public class OrgLevelServiceImpl implements OrgLevelService {
    private static Log log = LogFactory.getLog(OrgLevelServiceImpl.class);

	@Resource(name="orgLevelDao")
	private OrgLevelDao orgLevelDao;

	@SuppressWarnings("rawtypes")
	@Resource(name = "pageServiceImpl")
	private PagerService  pageServiceImpls;
	
	@Resource(name = "userServiceImpl")
	private UserService userServiceImpl;
	
	@Resource(name = "orgServiceImpl")
	private OrgService orgServiceImpl;
	
	


	@Override
	public Page getOrgLevelList(String levelName,String levelNumber,String enAbled, int from, int length)
			throws Exception {
		Page roleList;
		String hql = "from OrgLevel u where u.levelId is not null";
		if(levelName != null&&!levelName.trim().equals("")){
				hql += " and u.levelName like '%"+levelName+"%'";
		}
		if(levelNumber!=null&&!levelNumber.trim().equals("")){
			hql += " and u.levelNumber = '"+ levelNumber+"'";
		}
		if(enAbled!=null&&!enAbled.trim().equals("")){
			hql += " and u.enAbled = '"+enAbled+"'";
		}
		
		hql+=" order by u.createTime desc";
		
		try {
			roleList = pageServiceImpls.findPageByhqlQuery(from, length, hql);
			log.info("組織層級查找成功！");
		} catch (Exception e) {
			log.error("組織層級查找異常！",e);
			log.error(e.getMessage(), e);
			throw e;
		}
		return roleList;
		
	}

	//保存  add by 周歡歡
	@Override
	public String save(String levelName, int levelNumber, String enAbled, String levelId) {
		
		OrgLevel org = findOrgLevelByNumber(levelNumber);
		OrgLevel org1 = findOrgLevelByName(levelName);
		
		OrgLevel roleBean = new OrgLevel();
		OrgLevel findByIdBean = new OrgLevel();

		roleBean.setLevelName(levelName);
		roleBean.setLevelNumber(levelNumber);
		roleBean.setEnAbled(enAbled);
		roleBean.setCreateTime(new Date());
		roleBean.setCreateName("");
		roleBean.setUpdDt(new Date());
		roleBean.setUpdUser("");

		// 修改
		if (levelId != null && !levelId.trim().equals("")) {
			findByIdBean = findOrgLevelById(levelId);
			BeanUtils.copyProperties(roleBean, findByIdBean, new String[] { "levelId", "createTime", "createName" });// obj1複製到obj2
			// 四中修改後可以執行保存的情況
			if (org1 != null && org1.getLevelId().equals(levelId) && org != null && org.getLevelId().equals(levelId) || org1 != null && org1.getLevelId().equals(levelId) && org == null
					|| org1 == null && org != null && org.getLevelId().equals(levelId) || org1 == null && org == null) {
				try {
					orgLevelDao.saveOrUpdate(findByIdBean);
					log.info("修改成功！id="+levelId);
					return "SUCCESS";
				} catch (Exception e) {
					log.error("修改異常！id="+levelId,e);
					log.error(e.getMessage(), e);
					e.printStackTrace();
				}
			}
		// 新增
		} else {
			if (org == null && org1 == null) {
				try {
					orgLevelDao.saveOrUpdate(roleBean);
					log.info("新增成功！層級名稱="+levelName+"級別="+levelNumber);
					return "SUCCESS";
				} catch (Exception e) {
					log.error("新增異常！層級名稱="+levelName+"級別="+levelNumber,e);
					log.error(e.getMessage(), e);
					e.printStackTrace();
				}
			}
		}
		log.info("存在相同的層級名稱或者級別,層級名稱="+levelName+"級別="+levelNumber);
		return "LEVEL";
	}

	@Override
	public boolean deleteOrgLevel(String OrgLevelId) throws Exception {
		boolean flag = false;
		try {
			OrgLevel orgLevelBean=orgLevelDao.findById(OrgLevelId);
			orgLevelDao.delete(orgLevelBean);
			log.info("刪除成功！id="+OrgLevelId);
			flag = true;
		} catch (Exception e) {
			 log.error("刪除異常！id="+OrgLevelId, e);
	         log.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
		return flag;
	}

	@Override
	public OrgLevel findOrgLevelById(String orgLevelId) {
		
		try{
			OrgLevel orgLevelBean=orgLevelDao.findById(orgLevelId);
			log.info("根據ID查找成功，id="+orgLevelId);
			return orgLevelBean;
		} catch (Exception e) {
            log.error("根據ID查找異常，id="+orgLevelId, e);
            log.error(e.getMessage(), e);
            return null;
        }
	}
    //查找級別是否已經存在
	@Override
	public OrgLevel findOrgLevelByNumber(int orgLevelNumber) {
		List<OrgLevel> list = null;
		try {
			list = (List<OrgLevel>) orgLevelDao.findByProperty(OrgLevel.class, new String[] { "levelNumber" }, new Object[] { orgLevelNumber });
			log.info("查找級別為" + orgLevelNumber + "的組織層級成功！");
		} catch (Exception e) {
			log.error("查找級別為" + orgLevelNumber + "的組織層級異常！", e);
			log.error(e.getMessage(), e);
		}
		if (list != null && list.size() != 0) {
			return list.get(0);
		} else {
			return null;
		}
	}
	//查找組織層級名稱是否已經存在
	@Override
	public OrgLevel findOrgLevelByName(String orgLevelName) {
		List<OrgLevel> list = null;
		try {
			list = orgLevelDao.findByProperty(OrgLevel.class, new String[] { "levelName" }, new Object[] { orgLevelName });
			log.info("查找組織層級名稱為" + orgLevelName + "的組織層級成功！");
		} catch (Exception e) {
			log.error("查找組織層級名稱為" + orgLevelName + "的組織層級異常！", e);
			log.error(e.getMessage(), e);
		}
		if (list != null && list.size() != 0) {
			return list.get(0);
		} else {
			return null;
		}
	}
	
	/*public List<OrgLevel> findOrgByPreperty(String[] property,Object[] values){
		return orgLevelDao.findByProperty(OrgLevel.class, property, values);
	}*/
	
/*	@Override
	public String findNameByNumber(String createName) {
		MsAdminUser user = userServiceImpl.findUserByNo(createName);
		return user != null ? user.getRealName() : createName;
	}*/
	
	//判斷是否被占用  刪除時使用
	@Override
	public boolean isUsed(String orgLevelId) {
		List<Org> orgList = null;
		try {
			orgList = orgServiceImpl.findOrgByLevelId(orgLevelId);
			log.info("查找組織層級ID為" + orgLevelId + "的組織層級是否被佔用成功！");
		} catch (Exception e) {
			log.error("查找組織層級ID為" + orgLevelId + "的組織層級是否被佔用異常！", e);
			log.error(e.getMessage(), e);
		}
		if (orgList.size() > 0) {
			return true;
		}
		return false;
	}
}
